#name, wid, pa
namespace :bld do
  desc "Import CSV to database"
  task :save_history_data => :environment do
    require 'csv'
    pa = "#{BILI_PRO_PATH}#{ENV['pa']}\\"
    csv_file = File.open "#{pa}_list.csv"
    date_now =  Time.now
    puts "reading csv file..."
    csv_data = CSV::IOReader.new(csv_file)
    data = []
    csv_data.each do |row|
      data << { :wid => row[2], :name => row[3], :wtype => row[4], :author => row[5],
                :clicks => row[6], :clicks_rank => row[7], :comments => row[8], :comments_rank => row[9], :stows => row[10], :stows_rank => row[11],
                 :part => row[12], :score => row[1], :score_rank => row[0], :is_space_fix => (row[13].to_f < 1 && row[13].to_f > 0 ? true : nil)
              } unless row[0].to_i.zero?
    end
    except_ids = YAML.load(open(File.join("#{pa}except.yml")))
    begin
      weekly = Weekly.create! :name => ENV['name'], :wid => ENV['wid'], :last => Weekly.latest, :index => ENV['index'] || Weekly.maximum('"index"').to_i + 1
      WeeklyResult.transaction do
        puts "importing..."
        data.each do |d|
          WeeklyResult.create! d.merge(:weekly_id => weekly.id)
        end
      end
      WeeklyExcept.transaction do
        puts 'excepting...'
        except_ids.each do |wid|
          WeeklyExcept.create :weekly_id => weekly.id, :wid => wid if wid > 5
        end if except_ids
      end
    rescue
      p $!,$@
    end
    
    puts "#{Time.now - date_now} second complete"
  end
end
